<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div v-auth-dir="`park:enterprise:list`" class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button v-auth-dir="`park:enterprise:query`" type="primary" @click="searchFn">查询</el-button>
    </div>
    <div class="create-container">
      <el-button v-auth-dir="`park:rent:add_surrender`" type="primary" @click="$router.push('/add-ep')">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="enterpriseList" @expand-change="exChangeFn">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="scoped">
            <el-table :data="scoped.row.list">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="props">
                  <el-tag :type="formatterStatus(props.row.status)">{{ fontStatus[props.row.status] }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="{row}">
                  <el-button
                    v-auth-dir="`park:rent:add_surrender`"
                    size="mini"
                    type="text"
                    :disabled="!(row.status===1||row.status===2)"
                  >续租</el-button>
                  <el-button
                    v-auth-dir="`park:rent:add_surrender`"
                    size="mini"
                    type="text"
                    :disabled="(row.status===3)"
                    @click="outRentFn(row)"
                  >退租</el-button>
                  <el-button
                    v-auth-dir="`park:rent:remove`"
                    size="mini"
                    type="text"
                    :disabled="!(row.status===3)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          prop="contactNumber"
          label="联系电话"
        />
        <el-table-column label="操作">
          <template #default="scoped">
            <el-button
              v-auth-dir="`park:rent:add_surrender`"
              size="mini"
              type="text"
              @click="showAddRentDialog(scoped.row.id)"
            >添加合同</el-button>
            <el-button
              v-auth-dir="`park:rent:add_surrender`"
              size="mini"
              type="text"
              @click="$router.push(`/ep-detail?id=${scoped.row.id}`)"
            >查看</el-button>
            <el-button
              v-auth-dir="`park:rent:add_surrender`"
              size="mini"
              type="text"
              @click="openEpWindows('edit',scoped.row.id)"
            >编辑</el-button>
            <el-button
              v-auth-dir="`park:rent:remove`"
              size="mini"
              type="text"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="enterpriseTotal"
        :page-size="params.pageSize"
        layout="total, prev, pager, next"
        @current-change="handlePage"
      />
    </div>
    <!-- 点击添加合同 -->
    <el-dialog title="添加合同" :visible.sync="rentDialogVisible" width="580px" @close="closeReset">
      <!-- 表单区域 -->
      <div class="form-container" />
      <!-- 表单模版 -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              ref="uploadList"
              action="#"
              :http-request="uploadHandle"
              :before-upload="beforeUpload"
              :limit="1"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <!--
          slot="tip" 提示说明文字 Vue旧语法
          slot="tip" 等价于 v-solt:tip 或者 #tip
          slot-scope="scope" 等价于 v-slot="scope"
         -->
              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="{rentDialogVisible =false}">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getEnterpriseListAPI, getRentBuildListAPI, uploadAPI, createRentAPI, getRentListAPI, outRentAPI } from '@/apis/park'
export default {
  data() {
    return {
      // 设置租赁合同的文字
      fontStatus: {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      },
      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      enterpriseList: [], // 获取企业信息列表
      enterpriseTotal: 0,
      rentDialogVisible: false,
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: '', // 合同Url
        enterpriseId: null, // 企业id
        type: 0, // 合同类型 (0 租赁 ， 1 续租)
        rentTime: [] // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'change' }
        ],
        rentTime: [
          { required: true, message: '请选择租赁日期', trigger: 'change' }
        ],
        contractId: [
          { required: true, message: '请上传合同文件' }
        ]
      },
      buildList: [] // 楼宇信息
    }
  },
  created() {
    this.getEnterpriseList()
    this.getRentBuildList()
  },
  methods: {
    // 企业退租功能
    async outRentFn(row) {
      const id = row.id
      // const
      // console.log(id)
      this.$confirm('确定要退租吗？', '提示', {
        confirmButtonText: '确定',
        concelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await outRentAPI(id)
        // const res = await getRentListAPI(id)
        // eslint-disable-next-line no-undef
        // row.list = res.data
        this.getEnterpriseList()
        this.$message({
          type: 'success',
          message: '退租成功'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退租'
        })
      })
    },
    // 设置租赁合同的状态
    formatterStatus(status) {
      const obj = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return obj[status]
    },
    // 获取当前企业的合同信息
    async exChangeFn(row, rows) {
      // row：当前展开/ 关闭的这行数据对象
      // rows：所有展开行的数据对象
      if (rows.includes(row)) {
        const res = await getRentListAPI(row.id)
        // console.log(res)
        // eslint-disable-next-line require-atomic-updates
        row.list = res.data
      }
    },
    // 添加租赁合同
    async confirmAdd() {
      await this.$refs.addForm.validate()
      const obj = {
        ...this.rentForm
      }
      obj.startTime = this.rentForm.rentTime[0]
      obj.endTime = this.rentForm.rentTime[1]
      delete obj.rentTime
      const res = await createRentAPI(obj)
      // console.log(res)
      // 当文件上传成功后，需要清空表单，否则点开表单依然保留上一次数据
      this.$message({
        message: res.msg,
        type: 'success'
      })
      this.$refs.addForm.resetFields()
      this.$refs.uploadList.clearFiles()
      this.rentDialogVisible = false
    },
    // 上传传租赁合同
    async uploadHandle(file) {
      const theFile = file.file
      const fd = new FormData()
      fd.append('file', theFile)
      fd.append('type', 'contract')
      const res = await uploadAPI(fd)
      // console.log(res)
      this.rentForm.contractId = res.data.id
      this.rentForm.contractUrl = res.data.url
      // 合同上传后重新校验一次合同的rules
      await this.$refs.addForm.validateField('contractId')
    },
    // 上传前校验
    beforeUpload(file) {
      console.log(file)
      const list = ['application/msword', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      const isDoc = list.includes(file.type)
      const isSize = (file.size / 1024 / 1024 < 5)
      if (!isDoc) {
        this.$message.error('上传文件只能是 doc / docx / pdf 格式！')
      }
      if (!isSize) {
        this.$message.error('上传的文件大小不能超过5MB')
      }
      if (isDoc && isSize) {
        return true
      } else {
        return Promise.reject('取消上传')
      }
    },
    // 添加合同信息
    showAddRentDialog(id) {
      this.rentForm.enterpriseId = id
      // console.log(id)
      this.rentDialogVisible = true
      this.getRentBuildList()
    },
    // 获取企业信息列表
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      // 问题：运行后增加的对象的新属性，不可以直接让Vue正确的劫持到数据的变化，从而更新视图
      /**
       * 原因：Vue2用的 Object.defineProperty 劫持对象的每个属性的 setter（赋值）和getter（取值）-
       * enterpriseList 里的对象开始的时候只有5个属性
       * 解决方案：给 getEnterpriseList Vue的属性赋值让它被劫持之前，后端的数据对象先添加一个list再传给vue的属性
       */
      const list = res.data.rows.map(item => {
        return {
          ...item,
          list: []
        }
      })
      this.enterpriseList = list
      this.enterpriseTotal = res.data.total
      // console.log(this.enterpriseList)
      // console.log(res)
    },
    // 切换页面
    handlePage(page) {
      this.params.page = page
      this.getEnterpriseList()
    },
    // 搜索企业信息
    searchFn() {
      this.getEnterpriseList()
    },
    // 跳转至企业信息页面
    openEpWindows(type, id) {
      this.$router.push(`/add-ep?id=${id}&type=${type}`)
    },
    // 获取未租赁楼宇信息
    async getRentBuildList() {
      const res = await getRentBuildListAPI()
      // console.log(res)
      this.buildList = res.data
    },
    // 关闭弹窗是清空校验规则
    closeReset() {
      this.$refs.addForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
